import { useState, useCallback, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';
import { showNotification } from "../common/headerSlice";
import Pagination from "../../components/Pagination";
import CardService from "../../app/services/cardService";
import CommonService from "../../app/services/commonService";
import PlusIcon from "@heroicons/react/24/outline/PlusIcon";
import Datepicker from "react-tailwindcss-datepicker";
import TitleCard from "../../components/Cards/TitleCard";
import MagnifyingGlassIcon from "@heroicons/react/24/outline/MagnifyingGlassIcon";
import Tools from "../../utils/tools";
import _ from "lodash";

function Departments() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [data, setData] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [total, setTotal] = useState(0);
  const [dateValue, setDateValue] = useState({
    startDate: null,
    endDate: null
  });
  const [cardStatus, setCardStatus] = useState(0);
  const [cardNo, setCardNo] = useState("");
  const [cardInfo,setCardInfo] = useState({
    total:0,
    actived:0,
    remain:0
  })

  const fecthStatistics = () =>{
    CardService.statics().then((res) => {
      if (res.success) {
        setCardInfo(res.data);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    });
  }


  const fetchData = useCallback(() => {
    searchData(pageIndex);
    fecthStatistics();
  }, [pageIndex]);

  useEffect(() => {
    console.log("useEffect",searchData)
    fetchData();
  }, [pageIndex]);

  const onPageChange = (pageIndex) => {
    setPageIndex(pageIndex);
  }

  const handleDatePickerValueChange = (newValue) => {
    setDateValue(newValue);
  }

  const cardNoChanged = (e) => {
    setCardNo(e.target.value);
  }

  const cardStatusChange = (e) => {
    setCardStatus(e.target.value);
  }

  const onSearchingData = () => {
    setPageIndex(1);
    if(pageIndex === 1){
      searchData();
    }
  }

  const searchData = () => {
    console.log(pageIndex)
    
    const params = {
      startDate: dateValue.startDate || '',
      endDate: dateValue.endDate || '',
      cardNo: cardNo || '',
      cardStatus: cardStatus || '',
      pageIndex: pageIndex || 1,
    }

    CommonService.setLoading(true);
    CardService.list(params).then((res) => {
      if (res.success) {
        setData(res.data);
        setTotal(res.total);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }


  return (
    <>

      <div className="w-full p-4 card  bg-base-100">
        <div className="flex flex-col ">
          <div className="flex flex-row items-baseline justify-start">
            <div className="flex flex-row items-baseline justify-start mx-2">
              <div className="text-sm font-semibold">激活日期</div>
              <Datepicker
                containerClassName="w-72"
                value={dateValue}
                theme={"light"}
                inputClassName="input input-bordered w-60 mx-2"
                popoverDirection={"down"}
                toggleClassName="invisible"
                onChange={handleDatePickerValueChange}
                showShortcuts={true}
                primaryColor={"white"}
              />
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2">
              <div className="text-sm font-semibold">卡号</div>
              <input type="text" className="input input-bordered w-60  mx-2" value={cardNo} onChange={cardNoChanged} />
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2" >
              <div className="text-sm font-semibold">卡状态</div>
              <select className="select select-bordered w-60 mx-2" value={cardStatus} onChange={cardStatusChange}>
                <option selected value='0'>全部</option>
                <option value='1' >已激活</option>
                <option value='2'>未激活</option>
              </select>
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2">
              <button className="btn btn-sm bg-primary text-white" onClick={onSearchingData}><MagnifyingGlassIcon className="w-4 h-4" />查询</button>
            </div>
          </div>
        </div>
      </div>

      <div className="w-full card  bg-base-100 join join-horizontal flex flex-row items-center justify-center mt-4">
        <div class="flex-1 join-item bg-primary text-base-100 p-4 text-center">总计:<span className=" decoration-base-50">{cardInfo.totalCount}</span>张</div>
        <div class="flex-1 join-item bg-secondary  p-4 text-base-100 text-center">激活:<span>{cardInfo.activedCount}</span>张</div>
        <div class="flex-1 join-item bg-info  p-4 text-base-100 text-center">剩余:<span>{cardInfo.remainCount}</span>张</div>
      </div>

      <TitleCard title="卡管理" topMargin="mt-4" >
        <table className="table table-zebra bg-base-100 rounded-sm  border-1">
          <thead>
            <tr className=" border-b-2 border-base-100">
              <th className=" text-center">序号</th>
              <th className=" text-center">卡号</th>
              <th className=" text-center">状态</th>
              <th className=" text-center">激活日期</th>
              <th className=" text-center">发卡日期</th>
              <th className=" text-center">绑定考生</th>
              <th className=" text-center">考生学校</th>
              <th className=" text-center">规划师</th>
            </tr>
          </thead>
          <tbody>
            {data && data.length > 0 ? (
              data.map((item, index) => {
                return (
                  <tr key={index}>
                    <th className=" text-center">{(pageIndex-1)*10+ index +1}</th>
                    <td className=" text-center">{item.cardNo}</td>
                    <td className=" text-center">
                      {item.cardStatus === '未激活' ?
                      <span className="badge badge-info">{item.cardStatus}</span> :
                      <span className="badge badge-secondary">{item.cardStatus}</span>
                      }
                      </td>
                    <td className=" text-center">{item.activatedAt}</td>
                    <td className=" text-center">{item.createdAt}</td>
                    
                    <td className=" text-center">{item.activedName}</td>
                    <td className=" text-center">{item.schooleName}</td>
                    <td className=" text-center"></td>
  
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan="7">暂无数据</td>
              </tr>
            )}
          </tbody>
        </table>
        <div className="flex flex-row items-center justify-center">
          <Pagination currentPage={pageIndex} totalCount={total} onPageChange={onPageChange} />
        </div>
        <div className="flex flex-row items-start justify-between text-xs my-2 p-2 bg-base-300 rounded-md" style={{ lineHeight: '20px' }}>
          展示代理商卡片数量，包括激活数量、未激活数量，激活卡片绑定考生姓名等信息。
          </div>
      </TitleCard>
    </>
  );
}

export default Departments;
